import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService, UploadFile } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { HttpServcie } from '../../../../service/http.service';
import { Config } from '../../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { PartyBean } from '../bean/party.bean';

@Component({
  selector: 'party-add-page',
  templateUrl: 'party-add.html',
  styleUrls: ['party-add.scss']
})
export class PartyAddPage implements OnInit, OnChanges {
  validateForm: FormGroup;
  isSpinning: boolean = false;
  functions: any = [];
  @Input() inValue: any = [];
  @Output("outPut") outPut = new EventEmitter();
  //系统类型
  partyTypeList: any = Config.PARTY_TYPE;
  companyBean: PartyBean = new PartyBean();
  //省市区
  options: any = [];
  //地址
  addresOptions: any;
  config: any = Config;
  zzzsList: UploadFile[] = [];
  startList = [
    { value: "二星", label: "二星" },
    { value: "三星", label: "三星" },
    { value: "四星", label: "四星" },
    { value: "五星", label: "五星" }
  ];
  constructor(
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private _notification: NzNotificationService
  ) {
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      addresOptions: [null, [Validators.nullValidator]],//行政区划
      partyName: [null, [Validators.required]],//单位名称
      partyAddr: [null, [Validators.nullValidator]],//单位地址
      corporation: [null, [Validators.nullValidator]],//法人代表
      telephone: [null, [Validators.nullValidator]],//单位电话
      postalCode: [null, [Validators.nullValidator]],//邮政编码
      creditCode: [null, [Validators.nullValidator]],//组织机构代码
      businessLicenseNum: [null, [Validators.nullValidator]],//营业执照注册号
      contacts: [null, [Validators.nullValidator]],//所属行业
      industry: [null, [Validators.nullValidator]],//联系人
      contactsWork: [null, [Validators.nullValidator]],//联系人职务
      contactsCard: [null, [Validators.nullValidator]],//联系人身份证号
      contactsPhone: [null, [Validators.nullValidator]],//联系人电话
      contactsEmile: [null, [Validators.nullValidator]],//联系人邮箱
      contactsMobile: [null, [Validators.nullValidator]],//联系人手机
      contactsAddress: [null, [Validators.nullValidator]],//联系人地址
      agree: [null, [Validators.nullValidator]],
      partyType: [null, [Validators.required]],
      zzdj: [null, [Validators.nullValidator]],
      maintStart: [null, [Validators.nullValidator]],
    });
  }

  ngOnChanges() {
    this.functions = [];
    if (this.inValue) {
      this.functions = this.inValue;
    }
  }

  submitForm($event, data) {
    //校验是否能提交
    //没有填的标红
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }
    //处理是否提交
    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }
    //附件
    if (this.fileList.length > 0) {
      this.fileList.forEach(element => {
        this.companyBean.businessLicenseImg = element['response']['data'];
      })
    }
    if (this.zzzsList.length > 0) {
      this.zzzsList.forEach(element => {
        this.companyBean.zzzs = element["response"]["data"];
      });
      if (!this.companyBean.zzdj) {
        this._notification.create("error", "失败提示", "请输入资质等级");
        this.isSpinning = false;
        return;
      }
    }
    if (this.companyBean.partyType != '1') {
      this.companyBean.maintStart = null;
    }
    if (this.addresOptions) {
      //省
      this.companyBean.partyProvince = this.addresOptions[0];
      //市
      this.companyBean.partyCity = this.addresOptions[1];
      //区
      this.companyBean.partyArea = this.addresOptions[2];
    }
    this.isSpinning = true;
    this.companyBean.parentId = JSON.parse(window.localStorage['user']).partyId;
    let ob = this.httpServcie.addParty(this.companyBean);
    ob.subscribe((data) => {
      this.isSpinning = false;
      if (data.status == 200) {
        this._notification.create('success', '成功提示', '新增成功');
        this.outPut.emit($event);
      } else {
        this._notification.create('error', '失败提示', data.message);
        return;
      }
    })

  }

  //交验
  getFormControl2(name) {
    return this.validateForm.controls[name];
  }


  /** load data async  */
  loadData(e: { option: any, index: number, resolve: Function, reject: Function }): void {

    if (e.index === -1) {
      e.resolve(this.httpServcie.getProvince());
      return;
    }

    const option = e.option;
    option.loading = true;
    if (e.index === 0) {
      let values: any = option['value'];
      let valueList = this.httpServcie.getCity(e.option);
      let cities: any = {};
      cities[values] = valueList;

      setTimeout(() => {
        option.loading = false;
        e.resolve(cities[option.value]);
      }, 1);
    }
    if (e.index === 1) {
      let value = option['value'];
      let valueList = this.httpServcie.getRelation(e.option);
      let scenicspots: any = {};
      scenicspots[value] = valueList;
      setTimeout(() => {
        option.loading = false;
        e.resolve(scenicspots[option.value]);
      }, 1, scenicspots, option);
    }
  }

  handleChange2(info: { file: UploadFile }) {
    if (info.file.status === "uploading") {
      return;
    }
    if (info.file.status === "done") {
      //设置为接口的查询不然反显有时候没用
      this.zzzsList.forEach(element => {
        element["thumbUrl"] =
          this.config.IP +
          this.config.API.getUpload +
          "/" +
          element["response"]["data"];
      });
      // Get this url from response in real world.
    }
  }


  nzRemoveFile2 = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.zzzsList.length == 1) {
      this.zzzsList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.zzzsList.forEach((element, index) => {
      if (element["thumbUrl"] == file.thumbUrl) {
        this.zzzsList.splice(index, 1);
        this.zzzsList = this.zzzsList;
        list = this.zzzsList;
        this.zzzsList = [];
      }
    });
    list.forEach(element => {
      this.zzzsList.push(element);
    });
  };

  //文件上传
  previewImage = '';
  previewVisible = false;
  fileList: UploadFile[] = [];

  //查看
  handlePreview = (file: UploadFile) => {

    this.previewImage = this.config.IP + this.config.API.getUpload + "/" + file['response']['data'] || file.thumbUrl;
    this.previewVisible = true;
  }

  //查看
  handlePreview2 = (file: UploadFile) => {
    this.previewImage =
      this.config.IP +
      this.config.API.getUpload +
      "/" +
      file["response"]["data"] || file.thumbUrl;
    this.previewVisible = true;
  };

  /**
   * 上传就开始调用
   * @param info
   */
  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      //设置为接口的查询不然反显有时候没用
      this.fileList.forEach(element => {
        element['thumbUrl'] = this.config.IP + this.config.API.getUpload + "/" + element['response']['data'];
      })
      // Get this url from response in real world.
    }
  }

  //移除文件
  nzRemoveFile = (file: UploadFile) => {
    //移除fileList中的数据
    if (this.fileList.length == 1) {
      this.fileList = [];
      return;
    }
    let list: UploadFile[] = [];
    this.fileList.forEach((element, index) => {
      if (element['thumbUrl'] == file.thumbUrl) {
        this.fileList.splice(index, 1);
        this.fileList = this.fileList;
        list = this.fileList;
        this.fileList = [];
      }
    });
    list.forEach(element => {
      this.fileList.push(element);
    })
  }
}
